<?php
/**
 * GetIP
 * 取得真实IP
 * @staticvar string $realIp
 * @return string $Ip 
 * @package		
 * @author
 * 
 */
 
class Getip {


	public function __construct() {

	}

	public function getIp() {
    
		static $realIp = NULL;
		if ($realIp !== NULL) {
			return $realIp;
		}
		if (isset($_SERVER)) {
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR2'])) {
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR2']);
				/* 取X-Forwarded-For2中第?个非unknown的有效IP字符? */
				foreach ($arr as $ip) {
					$ip = trim($ip);
					if ($ip != 'unknown') {
						$realIp = $ip;
						break;
					}
				}
			} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
				/* 取X-Forwarded-For中第?个非unknown的有效IP字符? */
				foreach ($arr as $ip) {
					$ip = trim($ip);
					if ($ip != 'unknown') {
						$realIp = $ip;
						break;
					}
				}
			} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$realIp = $_SERVER['HTTP_CLIENT_IP'];
			} else {
				if (isset($_SERVER['REMOTE_ADDR'])) {
					$realIp = $_SERVER['REMOTE_ADDR'];
				} else {
					$realIp = '0.0.0.0';
				}
			}
		} else {
			if (getenv('HTTP_X_FORWARDED_FOR2')) {
				$realIp = getenv('HTTP_X_FORWARDED_FOR2');
			} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
				$realIp = getenv('HTTP_X_FORWARDED_FOR');
			} elseif (getenv('HTTP_CLIENT_IP')) {
				$realIp = getenv('HTTP_CLIENT_IP');
			} else {
				$realIp = getenv('REMOTE_ADDR');
			}
		}
		$onlineip = array();
		preg_match("/[\d\.]{7,15}/", $realIp, $onlineip);
		$realIp = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
		return $realIp;
	}

}
